<template>
  <div id="general-schedule">
    <Table :border="showBorder" :stripe="showStripe" :show-header="showHeader" :height="fixedHeader ? tableHeight : ''"
           :size="tableSize" :data="tableData" :columns="tableColumns" :loading="tableLoading" :disabledHover="disabledHover">
      <template slot-scope="{ row, index }" slot="weekday">
        <span>{{ row['weekday'].content || '' }}</span>
      </template>
      <template v-for="value in labList" slot-scope="{ row, index }" :slot="value.code">
        <div v-for="(content, index) in row[value.code]" :key="index">
          <div class="detail-link" @click="getDetail(content)">
            <span>课程：{{ content.courseName }}<span class="d-none">**</span></span>
            <br />
            <span>老师：{{ content.teacherName }}<span class="d-none">**</span></span>
            <br />
            <span v-for="item in content.classes.map(c => { return c.grade + c.major + c.sclass + '班' })" :key="item">
              <span>班级：{{ item }}<span class="d-none">**</span></span>
              <br />
            </span>
            <span>周次：{{ content.weekNumber.join('、') }}<span class="d-none">**</span></span>
          </div>
          <div v-if="index < row[value.code].length - 1">
            <Divider style="height: 1.5px; margin: 15px 0;" />
            <span class="d-none">**</span>
          </div>
        </div>
      </template>
    </Table>
    <div class="modal-container">
      <Modal v-model="modal.detail.show" footer-hide width="90%" class="mb-50-modal">
        <p slot="header" class="text-center" style="color: #276f86;">{{ modal.detail.title }}</p>
        <applied-form-detail-table v-if="modal.detail.show" :code="modal.detail.code" :title="modal.detail.title"/>
      </Modal>
    </div>
  </div>
</template>

<script>
import { getLabListByInstitute, getGeneralSchedule } from '@/api/general-schedule'
import AppliedFormDetailTable from '_c/applied-form-detail-table/applied-form-detail-table'
import { activeTableMove } from '@/libs/tools'
export default {
  name: 'GeneralSchedule',
  components: {
    'applied-form-detail-table': AppliedFormDetailTable
  },
  props: {
    filter: {
      type: Object,
      default: function () {
        return {
          institute: '',
          weekday: 'all'
        }
      }
    }
  },
  data () {
    return {
      firstEnter: false,
      weekdays: ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期天'],
      showBorder: true,
      showStripe: false,
      showHeader: true,
      tableData: [],
      labList: [],
      tableColumns: [],
      fixedHeader: true,
      tableHeight: '',
      disabledHover: true,
      tableLoading: false,
      tableSize: 'default',
      modal: {
        detail: {
          show: false,
          title: '',
          code: ''
        }
      }
    }
  },
  methods: {
    // 初始化表格表头
    initTableHeader: function () {
      this.tableColumns.push({
        title: '#',
        slot: 'weekday',
        key: 'weekday',
        align: 'center',
        width: 90,
        // fixed: 'left',
        className: 'row-combined'
      })
      this.tableColumns.push({
        title: '节次',
        key: 'section',
        align: 'center',
        // fixed: 'left',
        width: 70
      })
      this.labList.forEach(item => {
        this.tableColumns.push({
          title: item.code,
          slot: item.code,
          key: item.code,
          align: 'center',
          minWidth: 240,
          className: 'row-col-combined'
        })
      })
    },
    // 处理表格数据
    handleTableData (tableData) {
      let tempData = []
      tableData.forEach(data => {
        data.content.forEach((content, cIndex) => {
          content.cellClassName = {}
          let obj = {}
          // 星期几
          obj.weekday = {
            content: this.weekdays[data.week - 1],
            rowSpan: cIndex === 0 ? data.content.length : 1,
            cellShow: cIndex === 0
          }
          // 节次
          obj.section = cIndex + 1
          tempData.push({...obj, ...content})
        })
      })
      // 行合并（先上下合并）
      let n
      let m
      let len = tempData.length
      for (let j = 0; j < this.labList.length; j++) {
        let code = this.labList[j].code
        for (n = 0; n < len; n = m) {
          let item1 = tempData[n][code]
          if (Object.prototype.toString.call(item1) === '[object Array]') {
            let content1 = [...item1]
            item1.rowSpan = 1
            item1.show = true
            tempData[n].cellClassName[code] = 'custom-table-cell-style'
            for (m = n + 1; m < len; m++) {
              let item2 = tempData[m][code]
              if (Object.prototype.toString.call(item2) === '[object Array]') {
                let content2 = [...item2]
                item2.rowSpan = 1
                item2.show = true
                if (JSON.stringify(content1) === JSON.stringify(content2)) {
                  item1.rowSpan++
                  item2.show = false
                } else {
                  break
                }
              } else {
                break
              }
            }
          } else {
            m = n + 1
          }
        }
      }
      // 列合并（再左右合并）
      for (let i = 0, length = tempData.length; i < length; i++) {
        let j
        let k
        for (j = 0; j < this.labList.length; j = k) {
          let labCode1 = this.labList[j].code
          let item1 = tempData[i][labCode1]
          if (Object.prototype.toString.call(item1) === '[object Array]') {
            item1.colSpan = 1
            for (k = j + 1; k < this.labList.length; k++) {
              let labCode2 = this.labList[k].code
              let item2 = tempData[i][labCode2]
              if (Object.prototype.toString.call(item2) === '[object Array]') {
                let content1 = JSON.parse(JSON.stringify(item1))
                delete content1.colSpan
                delete content1.rowSpan
                delete content1.show
                let content2 = JSON.parse(JSON.stringify(item2))
                delete content2.rowSpan
                delete content2.show
                item2.colSpan = 1
                if (JSON.stringify(content1) === JSON.stringify(content2)) {
                  item1.colSpan++
                  item2.show = false
                } else {
                  break
                }
              } else {
                break
              }
            }
          } else {
            k = j + 1
          }
        }
      }
      return tempData
    },
    // 获取数据渲染表格
    async renderTable (filter) {
      // 初始化表格
      this.tableLoading = true
      this.labList = []
      this.tableData = []
      this.tableColumns = []
      try {
        // 根据学院获取实验室
        let response = await getLabListByInstitute(filter.institute)
        let res = response.data
        if (res.code === 1) {
          this.labList = res.data.length > 0 ? res.data.map(item => {
            return {
              'name': item.name,
              'code': item.code
            }
          }) : []
          // 加载表头
          this.initTableHeader()
          // 获取表格数据
          try {
            let response = await getGeneralSchedule(filter)
            let res = response.data
            if (res.code === 1) {
              if (res.data.length > 0) {
                // 处理表格数据
                this.tableData = this.handleTableData(res.data)
                // 设置表格单元的行合并和列合并
                this.$nextTick(() => {
                  // document.querySelectorAll('#general-schedule .ivu-table-fixed-body td.row-combined').forEach((item, index) => {
                  //   item.setAttribute('rowspan', this.tableData[index].weekday.rowSpan)
                  //   item.style.display = this.tableData[index].weekday.cellShow ? '' : 'none'
                  // })
                  document.querySelectorAll('#general-schedule .ivu-table-body td.row-combined').forEach((item, index) => {
                    item.setAttribute('rowspan', this.tableData[index] ? this.tableData[index].weekday.rowSpan : 1)
                    item.style.display = this.tableData[index].weekday.cellShow ? '' : 'none'
                    if (!this.tableData[index].weekday.cellShow) {
                      item.parentNode.removeChild(item)
                    }
                  })
                  document.querySelectorAll('#general-schedule .ivu-table-body td.row-col-combined').forEach((item, index) => {
                    let row = this.tableData[Math.floor(index / this.labList.length)]
                    let cell = this.labList[index % this.labList.length].code
                    if (row[cell]) {
                      item.setAttribute('colspan', row[cell].colSpan || 1)
                      item.setAttribute('rowspan', row[cell].rowSpan || 1)
                      item.style.display = row[cell].show ? '' : 'none'
                      if (!row[cell].show) {
                        item.parentNode.removeChild(item)
                      }
                    }
                  })
                  this.tableLoading = false
                })
              }
            } else {
              this.tableColumns = []
              this.tableLoading = false
              this.$Notice.error({
                title: '列表加载失败',
                desc: '总体安排表加载失败！' + res.info
              })
            }
          } catch (error) {
            this.tableColumns = []
            this.tableLoading = false
            this.$Notice.error({
              title: '列表加载失败',
              desc: '总体安排表加载失败！'
            })
            console.log(error)
          }
        } else {
          this.tableColumns = []
          this.tableLoading = false
          this.$Notice.error({
            title: '列表加载失败',
            desc: '总体安排表加载失败！' + res.info
          })
        }
        this.$nextTick(() => {
          this.tableLoading = false
        })
      } catch (error) {
        this.tableColumns = []
        this.tableLoading = false
        this.$Notice.error({
          title: '列表加载失败',
          desc: '总体安排表加载失败！'
        })
        console.log(error)
      }
    },
    // 查看详情
    getDetail (content) {
      this.modal.detail.title = content.teacherName + '老师的' + '《' + content.courseName + '》课程相关的实验课信息登记表'
      this.modal.detail.show = true
      this.modal.detail.code = content.code || ''
    }
  },
  created () {
    this.firstEnter = true
    this.$Notice.config({
      top: window.innerHeight / 3
    })
  },
  mounted () {
    this.$nextTick(() => {
      activeTableMove(document.querySelector('#general-schedule .ivu-table-body'))
    })
  },
  activated () {
    if (!this.firstEnter) {
      this.$Notice.config({
        top: window.innerHeight / 3
      })
    }
  },
  deactivated () {
    this.firstEnter = false
    this.$Notice.destroy()
  },
  beforeDestroy () {
    this.$Notice.destroy()
  },
  watch: {
    filter: {
      handler: function (value) {
        // let state = true
        // for (let key in value) {
        //   if (value.hasOwnProperty(key)) {
        //     if (!value[key]) {
        //       state = false
        //       break
        //     }
        //   } else {
        //     state = false
        //     break
        //   }
        // }
        // if (state) {
        //   this.renderTable(value)
        // }
        this.renderTable(value)
      },
      deep: true
    }
  }
}
</script>

<style lang="less" scoped>
  #general-schedule {
    /*.ivu-table-wrapper {*/
    /*border-top: .2em solid #f44336;*/
    /*border-radius: .3rem;*/
    /*}*/
  }
</style>
<style lang="less">
  #general-schedule {
    .custom-table-cell-style {
      background-color: #ebf7ff !important;
      color: #276f86 !important;
    }
    .ivu-table {
      &-tbody {
        .ivu-table-cell {
          padding-top: 10px;
          padding-bottom: 10px;
          font-size: 0.825rem;
          font-weight: bold;
        }
      }
      &-wrapper {
        border-color: #ccc;
      }
      &-border {
        & th {
          border-color: #ccc;
        }
        & td {
          border-color: #ccc;
        }
      }
      .detail-link {
        line-height: 1.5rem;

        &:hover {
          cursor: pointer;
          color: #2D8cF0;
          text-decoration: underline;
        }
      }
    }
  }
</style>
